package cn.z2huo.demo.spring.transactional.service.programmatic;

import cn.z2huo.core.util.IdUtils;
import cn.z2huo.demo.mapper.user.UserMapper;
import cn.z2huo.demo.model.dataobject.user.UserDO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;

@Slf4j
@Service
public class TransactionTemplateServiceImpl {

    @Autowired
    private TransactionTemplate transactionTemplate;

    @Autowired
    private UserMapper userMapper;

    public void insertUser() {

        transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus status) {

                UserDO userDO = new UserDO()
                        .setId(IdUtils.nextId())
                        .setUserCode("18182222")
                        .setUserName("tx-template user " + RandomStringUtils.randomAlphabetic(4));
                userMapper.insertSelective(userDO);
                log.info("insertUser end");
            }
        });
        log.info("tx end");
    }

    public void insertUser2() {
        transactionTemplate.executeWithoutResult(status -> {
            UserDO userDO = new UserDO()
                    .setId(IdUtils.nextId())
                    .setUserCode("18182222")
                    .setUserName("tx-template user " + RandomStringUtils.randomAlphabetic(4));
            userMapper.insertSelective(userDO);
            log.info("insertUser end");
        });
        log.info("tx end");
    }

    public String insertUserHaveReturn() {

        Integer executeResult = transactionTemplate.execute(status -> {
            UserDO userDO = new UserDO()
                    .setId(IdUtils.nextId())
                    .setUserCode("18182222")
                    .setUserName("tx-template user " + RandomStringUtils.randomAlphabetic(4));
            int result = userMapper.insertSelective(userDO);
            log.info("insertUser end");
            return result;
        });
        return Integer.valueOf(1).equals(executeResult) ? "success" : "fail";
    }

    public int insertUserNoTx() {
        UserDO userDO = new UserDO()
                .setId(IdUtils.nextId())
                .setUserCode("18182222")
                .setUserName("no tx user " + RandomStringUtils.randomAlphabetic(4));
        int result = userMapper.insertSelective(userDO);
        return result;
    }

}
